<template>
	<div class="boxStyle">
		<el-row type="flex" class="row-bg" justify="start" style="margin-bottom: 10px;">
			<el-col :span="1" style="margin-top: 5px;">名称 :</el-col>
			<el-col :span="3">
				<el-input v-model="name" size="small"></el-input>
			</el-col>
			<el-col :span="1" style="margin-left: 20px;margin-top: 5px; ">卡券编码 :</el-col>
			<el-col :span="3">
				<el-input v-model="goodsCode" size="small"></el-input>
			</el-col>
			<el-col :span="1" style="margin-left: 20px;margin-top: 5px;">类别 :</el-col>
			<el-col :span="2">
				<el-select v-model="typeId" placeholder="请选择" size="small">
					<el-option value="" label="全部"></el-option>
					<el-option v-for="item in typelists" :key="item.id" :label="item.name" :value="item.id">
					</el-option>
				</el-select>
			</el-col>
			<el-col :span="1" style="margin-left: 20px;margin-top: 5px;">状态 :</el-col>
			<el-col :span="2">
				<el-select v-model="status" placeholder="请选择" size="small">
					<el-option value="" label="全部"></el-option>
					<el-option value="0" label="下架"></el-option>
					<el-option value="1" label="上架"></el-option>
				</el-select>
			</el-col>
			<el-col :span="1" style="margin-left:50px;">
				<el-button type="warning" size="small" @click="search" icon="el-icon-search">查找</el-button>
			</el-col>
			<el-col :span="1" style="margin-left:50px;" v-if="addShow!==-1">
				<el-button type="warning" size="small" @click="add" icon="el-icon-plus">新增</el-button>
			</el-col>
		</el-row>
		<el-table ref="multipleTable" stripe border :data="tableLists" tooltip-effect="dark" style="margin-bottom: 10px;width: 100%">
			<el-table-column type="selection" width="55"></el-table-column>
			<el-table-column prop="id" label="ID" width="55"></el-table-column>
			<el-table-column prop="name" label="卡券名称" width="200"></el-table-column>
			<el-table-column prop="goodsCode" label="卡券编码" width="120"></el-table-column>
			<el-table-column prop="typeName" label="卡券分类" width="120"></el-table-column>
			<el-table-column prop="status" label="状态" width="120">
				<template slot-scope="scope">
					<span v-if="scope.row.status==0" style="color: red;">下架</span>
					<span v-else>上架</span>
				</template>
			</el-table-column>
			<el-table-column prop="isDistri" label="分销" width="120">
				<template slot-scope="scope">
					<span v-if="scope.row.isDistri ==1" style="color: red;">是</span>
					<span v-if="scope.row.isDistri ==0">否</span>
				</template>
			</el-table-column>
			<el-table-column prop="sort" sortable label="排序" width="120"></el-table-column>
			<el-table-column prop="isShow" label="列表显示" width="120">
				<template slot-scope="scope">
					<span v-if="scope.row.isShow==0" style="color: red;">不显示</span>
					<span v-if="scope.row.isShow==1">显示</span>
				</template>
			</el-table-column>
			<!--<el-table-column prop="id" label="链接" width="180">
				<template slot-scope="scope">{{imgurl}}cardDetails.html?cardsId={{scope.row.id}}</template>
			</el-table-column>-->
			<el-table-column label="操作" min-width="120">
				<template slot-scope="scope">
					<el-button size="mini" type="primary" v-if="updateShow!==-1" @click="update(scope.$index,scope.row.id)">编辑</el-button>
					<el-button size="mini" style="margin-top: 5px;margin-left: 0px;" type="danger" v-if="scope.row.isShow==0&&btnisShow!==-1" @click="updateShowStatus(scope.row.id, 1)">显示</el-button>
					<el-button size="mini" style="margin-top: 5px;margin-left: 0px;" type="danger" v-if="scope.row.isShow==1&&btnisShow!==-1" @click="updateShowStatus(scope.row.id, 0)">隐藏</el-button>
					<el-button size="mini" style="margin-top: 5px;margin-left: 0px;" type="danger" v-if="scope.row.status==0&&btnstatus!==-1" @click="updateStatus(scope.row.id, 1)">上架</el-button>
					<el-button size="mini" style="margin-top: 5px;margin-left: 0px;" type="danger" v-if="scope.row.status==1&&btnstatus!==-1" @click="updateStatus(scope.row.id, 0)">下架</el-button>
				</template>
			</el-table-column>
		</el-table>
		<el-pagination background @current-change="handleCurrentChange" :current-page="currentPage" :page-size="size" layout="prev, pager, next,total, slot" :total="totals">
			<span style="margin-top: -2px;color: #606266;font-weight: 100;">第<el-input type="text" v-model="inputPage" style="width: 60px;margin: 0 5px;"/>页<el-button size="mini" style="background: #409EFF; color: #fff;margin:0 5px;" @click="handleCurrentChange(inputPage)">跳转</el-button><span>总计{{totalPage}}页</span></span>
		</el-pagination>
		<div class="modal fade" id="cards" tabindex="-1" role="dialog" data-keyboard="false">
			<div class="modal-dialog" role="document">
				<div class="modal-content" style="width:1200px;height: 750px;">
					<div class="modal-header" style="border-radius: 4px;">
						<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
						<ul class="nav nav-tabs cards" role="tablist">
							<li role="presentation" class="active">
								<a href="#qusInfo" aria-controls="qusInfo" role="tab" data-toggle="tab">新增/编辑</a>
							</li>
						</ul>
					</div>
					<div class="modal-body" style="padding-right: 60px;height:600px;overflow: hidden;overflow-y: auto;">
						<div class="tab-content">
							<div role="tabpanel" class="tab-pane active" id="qusInfo">
								<el-form :model="rulecards" :rules="rules" ref="rulecards" label-width="100px" class="demo-ruleForm">
									<input type="hidden" name="id" id="id" v-model="id" />
									<el-col :span="12">
										<el-form-item label="名称:" prop="name" :rules="MUSTINFO">
											<el-input v-model="rulecards.name" size="small"></el-input>
										</el-form-item>
									</el-col>
									<el-col :span="12">
										<el-form-item label="简介 :" prop="infoDetail" :rules="MUSTINFO">
											<el-input type="textarea" :autosize="{ minRows: 2, maxRows: 4}" placeholder="最多输入225个字" :maxlength=225 v-model="rulecards.infoDetail">
											</el-input>
										</el-form-item>
									</el-col>
									<el-col :span="12">
										<el-form-item label="分类:" prop="typeId" :rules="MUSTINFO">
											<el-select v-model="rulecards.typeId" size="small" style="width: 262px;">
												<el-option v-for="item in typelists" :key="item.id" :label="item.name" :value="item.id"></el-option>
											</el-select>
										</el-form-item>
									</el-col>
									<el-col :span="12">
										<el-form-item label="编码:" prop="goodsCode" :rules="MUSTINFO">
											<el-input v-model="rulecards.goodsCode" size="small"></el-input>
										</el-form-item>
									</el-col>
									<el-col :span="12">
										<el-form-item label="售价:" prop="salesPrice" :rules="MUSTINFO">
											<el-input v-model="rulecards.salesPrice" size="small"></el-input>
										</el-form-item>
									</el-col>
									<el-col :span="12">
										<el-form-item label="原价:" prop="originalPrice" :rules="MUSTINFO">
											<el-input v-model="rulecards.originalPrice" size="small"></el-input>
										</el-form-item>
									</el-col>
									<el-col :span="12">
										<el-form-item label="库存:" prop="stock" :rules="MUSTNUMBER">
											<el-input v-model.number="rulecards.stock" size="small"></el-input>
										</el-form-item>
									</el-col>
									<el-col :span="12">
										<el-form-item prop="useTime" label="使用时间:" :rules="MUSTINFO">
											<el-date-picker v-model="rulecards.useTime" type="datetimerange" range-separator="至" start-placeholder="开始时间" end-placeholder="结束时间"></el-date-picker>
										</el-form-item>
									</el-col>
									<el-col :span="24">
										<el-col :span="6">
											<el-form-item label="限购 :" prop="limitBuy" :rules="MUSTINFO">
												<el-radio-group v-model="rulecards.limitBuy" style="margin-top:5px;">
													<el-radio label="0">不限购</el-radio>
													<el-radio label="1">开启限购</el-radio>
												</el-radio-group>
											</el-form-item>
										</el-col>
										<el-col :span="6" v-if="rulecards.limitBuy==1">
											<el-form-item prop="limitBuyCount" label="限购数量:">
												<el-input v-model.number="rulecards.limitBuyCount" size="small"></el-input>
											</el-form-item>
										</el-col>
										<el-col :span="8" v-if="rulecards.limitBuy==1">
											<el-form-item prop="limitTime" label="限购时间:">
												<el-date-picker v-model="rulecards.limitTime" type="datetimerange" range-separator="至" start-placeholder="开始时间" end-placeholder="结束时间"></el-date-picker>
											</el-form-item>
										</el-col>
									</el-col>
									<el-col :span="12">
										<el-form-item label="销量偏移:" prop="salesAdd" :rules="MUSTNUMBER">
											<el-input v-model.number="rulecards.salesAdd" size="small"></el-input>
										</el-form-item>
									</el-col>
									<el-col :span="12">
										<el-form-item label="排序:" prop="sort" :rules="MUSTNUMBER">
											<el-col :span="12">
												<el-input v-model.number="rulecards.sort" size="small"></el-input>
											</el-col>
											<el-col :span="12">
												<span style="color: red;">（排序越大,越靠前。只能是数字）</span>
											</el-col>
										</el-form-item>
									</el-col>
									<el-col :span="12">
										<el-form-item label="列表显示:" prop="isShow" :rules="MUSTINFO">
											<el-radio-group v-model="rulecards.isShow" style="margin-top:5px;">
												<el-radio label="0">不显示</el-radio>
												<el-radio label="1">显示</el-radio>
											</el-radio-group>
										</el-form-item>
									</el-col>
									<el-col :span="12">
										<el-form-item label="参与分销:" prop="isDistri" :rules="MUSTINFO">
											<el-radio-group v-model="rulecards.isDistri" style="margin-top:5px;">
												<el-radio label="0">关闭</el-radio>
												<el-radio label="1">开启</el-radio>
											</el-radio-group>
										</el-form-item>
									</el-col>
									<el-col :span="12">
										<el-form-item label="所属渠道商:" prop="channelId" :rules="MUSTINFO">
											<el-select v-model="rulecards.channelId" placeholder="请选择" size="small" style="width: 180px;">
												<el-option v-for="item in channelList" :key="item.id" :label="item.name" :value="item.id">
												</el-option>
											</el-select>
										</el-form-item>
									</el-col>
									<el-col :span="24">
										<el-form-item label="主图:">
											<el-upload class="upload-demo" name="file" :action="url" list-type="picture-card" :file-list="mainImg" :onSuccess="uploadSuccess" :on-remove="uploadremove">
												<el-button size="mini" type="primary">选择本地图片</el-button>
											</el-upload>
										</el-form-item>
									</el-col>
									<el-col :span="24">
										<el-form-item label="内容:">
											<ueditor v-model="form.content" id="cardseditor" ref="cardseditor" style="width:100%"></ueditor>
										</el-form-item>
									</el-col>
								</el-form>
							</div>
						</div>
					</div>
					<div class="modal-footer">
						<el-button type="success" size="small" id="save" @click="save('rulecards')" :loading="loading">保存</el-button>
						<el-button type="success" size="small" id="usave" @click="uSave('rulecards')" :loading="loading">保存</el-button>
						<button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
					</div>
				</div>
			</div>
			<div></div>
		</div>
	</div>
</template>

<script>
	import axios from "axios"
	import qs from "qs"
	import ueditor from "components/ueditor.vue"
	import { MUSTNUMBER, MUSTINFO } from 'static/js/rules.js'
	import { formatDate } from 'static/js/date.js'
	export default {
		data() {
			var limitBuy = (rule, value, callback) => {
				if(this.rulecards.limitBuy == 1) {
					if(value == "" || value == null) {
						return callback(new Error('该项为必填'));
					} else {
						callback()
					}
				}
			};
			return {
				status: "",
				typeId: "",
				goodsCode: '',
				name: '',
				MUSTINFO,
				MUSTNUMBER,
				currentPage: 1, //当前页
				totals: 0, //分页总条数
				size: 0, //每页条数
				tableLists: [],
				statuslists: [],
				url: this.GLOBAL.url,
				imgurl: this.GLOBAL.imgurl,
				typelists: [],
				inputPage: 1,
				totalPage: 0, //总页数
				purl: this.$store.state.purl, //权限数组
				updateShow: 0, //是否显示更新信息
				addShow: 0, //是否显示新增
				btnisShow: 0,
				btnstatus: 0,
				id: "",
				skuId: "",
				version: "",
				rulecards: {
					channelId: '',
					goodsCode: '',
					infoDetail: '',
					isDistri: '0',
					isShow: '1',
					limitBuy: '0',
					limitBuyCount: "",
					name: '',
					originalPrice: '',
					salesAdd: '',
					salesPrice: '',
					sort: '',
					stock: '',
					typeId: '',
					limitTime: [],
					useTime: []
				},
				rules: {
					limitBuyCount: [{
						validator: limitBuy,
						trigger: 'blur'
					}],
					limitTime: [{
						validator: limitBuy,
						trigger: 'blur'
					}],
				},
				types: [],
				protabs: [],
				storetabs: [],
				storeName: [],
				isIndeterminate: true,
				checkAll: false,
				mainImg: [],
				form: {
					content: ""
				},
				channelList: [],
				loading: false,
			}
		},
		components: {
			ueditor
		},
		activated() {
			this.name = "";
			this.goodsCode = "";
			this.typeId = "";
			this.status = "";
			this.load(1);
			this.currentPage = 1;
			this.inputPage = this.currentPage;
			this.addShow = this.purl[0].findIndex((val) => val === "/interface/goods/add") //判断是否拥有增加权限
			this.updateShow = this.purl[0].findIndex((val) => val === "/interface/goods/add") //判断是否拥有更新权限
			this.btnisShow = this.purl[0].findIndex((val) => val === "/interface/goods/add")
			this.btnstatus = this.purl[0].findIndex((val) => val === "/interface/goods/add")
		},
		methods: {
			load(num) {
				axios.get("/interface/goods/list?pageNo=" + num).then((res) => {
					this.tableLists = res.data.data.list; //list数据
					this.totals = res.data.data.pageBean.totalRow; //总条数
					this.size = res.data.data.pageBean.pageSize; //每页条数
					this.totalPage = res.data.data.pageBean.totalPage; //总页数
					this.typelists = res.data.data.typelist;
				})
			},
			handleCurrentChange(val) {
				this.currentPage = val - 0;
				this.inputPage = val;
				//查找的分页跳转
				axios.post("/interface/goods/list?", qs.stringify({
					name: this.name,
					goodsCode: this.goodsCode,
					typeId: this.typeId,
					status: this.status,
					pageNo: val
				})).then((res) => {
					this.tableLists = res.data.data.list; //list数据
					this.totals = res.data.data.pageBean.totalRow; //总条数
					this.size = res.data.data.pageBean.pageSize; //每页条数
					this.totalPage = res.data.data.pageBean.totalPage; //总页数
					this.typelists = res.data.data.typelist;
				})
			},
			search() {
				axios.post("/interface/goods/list?", qs.stringify({
					name: this.name,
					goodsCode: this.goodsCode,
					typeId: this.typeId,
					status: this.status,
					pageNo: 1
				})).then((res) => {
					this.tableLists = res.data.data.list; //list数据
					this.totals = res.data.data.pageBean.totalRow; //总条数
					this.size = res.data.data.pageBean.pageSize; //每页条数
					this.totalPage = res.data.data.pageBean.totalPage; //总页数
					this.typelists = res.data.data.typelist;
				})
			},
			updateStatus(cardsId, status) {
				var msg = ""
				if(status == 1) {
					msg = "确认上架该产品吗";
				} else if(status == 0) {
					msg = "确认下架该产品吗";
				} else {
					return;
				}
				this.$confirm(msg, '提示', {
					confirmButtonText: '确定',
					cancelButtonText: '取消',
					type: 'warning'
				}).then((res) => {
					axios({
						method: 'post',
						url: '/interface/goods/add',
						data: {
							"id": cardsId,
							"status": status
						},
						headers: {
							'Content-Type': 'application/json'
						}
					}).then((res) => {
						this.load(1)
					})
					this.$message({
						type: 'success',
						message: '操作成功!'
					});
				}).catch(() => {})
			},
			updateShowStatus(cardsId, isShow) {
				this.$confirm('确认要更改列表状态吗?', '删除警告', {
					confirmButtonText: '确定',
					cancelButtonText: '取消',
					type: 'warning'
				}).then(() => {
					axios({
						method: 'post',
						url: '/interface/goods/add',
						data: {
							"id": cardsId,
							"isShow": isShow
						},
						headers: {
							'Content-Type': 'application/json'
						}
					}).then((res) => {
						this.load(1)
					})
					this.$message({
						type: 'success',
						message: '操作成功!'
					});
				}).catch(() => {});
			},
			add() {
				$("#cards").modal("show");
				$("#save").show();
				$("#usave").hide();
				this.rulecards = {
						channelId: '',
						goodsCode: '',
						infoDetail: '',
						isDistri: '0',
						isShow: '1',
						limitBuy: '0',
						limitBuyCount: "",
						name: '',
						originalPrice: '',
						salesAdd: '',
						salesPrice: '',
						sort: '',
						stock: '',
						typeId: '',
						limitTime: [],
						useTime: []
					},
					this.mainImg = [];
					this.form = {content: ""};
				axios.get("/interface/goods/view").then((res) => {
					this.channelList = res.data.data.list
				})
			},
			save(formname) {
				this.$refs[formname].validate((valid) => {
					if(valid) {
						if(this.mainImg == "" || this.mainImg.length == 0) {
							this.$message.error("请至少上传一张配图");
							return;
						}
						if(this.form.content == "" || this.form.content.length == 0) {
							this.$message.error("请输入文章内容");
							return;
						}
						if(this.rulecards.limitBuy == 1) {
							this.rulecards.limitStime = new Date(this.rulecards.limitTime[0])
							this.rulecards.limitEtime = new Date(this.rulecards.limitTime[1])
						}

						this.rulecards.stime = new Date(this.rulecards.useTime[0])
						this.rulecards.etime = new Date(this.rulecards.useTime[1])
						this.loading = true;
						//主图
						var mimgLength = this.mainImg.length;
						var imagesStr = "[";
						for(var i = 0; i < mimgLength; i++) {
							imagesStr += "{image:'" + this.mainImg[i].url.replace(this.imgurl, "") +
								"',goodsId:" + 0 + "},"
						}
						imagesStr += "]";
						this.rulecards.description = this.form.content;
						this.rulecards.mainPic = JSON.stringify(eval('(' + imagesStr + ')'));
						axios({
							method: 'post',
							url: '/interface/goods/add',
							data: this.rulecards,
							headers: {
								'Content-Type': 'application/json'
							}
						}).then((res) => {
							if(res.data.code == 1) {
								$("#cards").modal("hide");
								this.load(this.currentPage);
								this.$message.success("新增成功")
								this.loading = false;
							} else {
								var msg = res.data.msg;
								$("#cards").modal("hide");
								this.loading = false;
								this.$alert(msg, '提示消息', {
									confirmButtonText: '确定',
									callback: action => {
										$("#cards").modal("show");
									}
								});
							}
						});
					} else {
						return false;
					}
				})
			},
			update(index, id, version) {
				$("#cards").modal("show");
				$("#save").hide();
				$("#usave").show();
				this.id = id;
				axios.get("/interface/goods/view?id=" + id).then((res) => {
					this.rulecards = res.data.data.goods;
					this.channelList = res.data.data.list
					var that = this;
					that.mainImg = [];
					$.each(JSON.parse(res.data.data.goods.mainPic), function(idx, item) {
						that.mainImg.push({
							name: idx,
							url: that.imgurl + item.image
						})
					})
					this.form.content = res.data.data.goods.description;
					if(res.data.data.goods.limitStime == '' || res.data.data.goods.limitStime == null) {
						this.$set(this.rulecards, "limitTime", [])
					} else {
						this.$set(this.rulecards, "limitTime", [res.data.data.goods.limitStime, res.data.data.goods.limitEtime])
					}
					if(res.data.data.goods.stime == '' || res.data.data.goods.stime == null) {
						this.$set(this.rulecards, "useTime", [])
					} else {
						this.$set(this.rulecards, "useTime", [res.data.data.goods.stime, res.data.data.goods.etime])
					}
					this.rulecards.isDistri = res.data.data.goods.isDistri.toString();
					this.rulecards.isShow = res.data.data.goods.isShow.toString();
					this.rulecards.limitBuy = res.data.data.goods.limitBuy.toString();
				})
			},
			uSave(formname) {
				this.$refs[formname].validate((valid) => {
					if(valid) {
						if(this.mainImg == "" || this.mainImg.length == 0) {
							this.$message.error("请至少上传一张配图");
							return;
						}
						if(this.form.content == "" || this.form.content.length == 0) {
							this.$message.error("请输入文章内容");
							return;
						}
						if(this.rulecards.limitBuy == 1) {
							this.rulecards.limitStime = new Date(this.rulecards.limitTime[0])
							this.rulecards.limitEtime = new Date(this.rulecards.limitTime[1])
						}

						this.rulecards.stime = new Date(this.rulecards.useTime[0])
						this.rulecards.etime = new Date(this.rulecards.useTime[1])
						this.loading = true;
						//主图
						var mimgLength = this.mainImg.length;
						var imagesStr = "[";
						for(var i = 0; i < mimgLength; i++) {
							imagesStr += "{image:'" + this.mainImg[i].url.replace(this.imgurl, "") +
								"',goodsId:" + 0 + "},"
						}
						imagesStr += "]";
						this.rulecards.description = this.form.content;
						this.rulecards.mainPic = JSON.stringify(eval('(' + imagesStr + ')'));
						axios({
							method: 'post',
							url: '/interface/goods/add',
							data: this.rulecards,
							headers: {
								'Content-Type': 'application/json'
							}
						}).then((res) => {
							if(res.data.code == 1) {
								$("#cards").modal("hide");
								this.load(this.currentPage);
								this.$message.success("更新成功")
								this.loading = false;
							} else {
								var msg = res.data.msg;
								$("#cards").modal("hide");
								this.loading = false;
								this.$alert(msg, '提示消息', {
									confirmButtonText: '确定',
									callback: action => {
										$("#cards").modal("show");
									}
								});
							}
						});
					} else {
						return false;
					}
				})
			},
			uploadSuccess(file, fileList) {
				var img = {
					uid: fileList.uid,
					url: this.imgurl + file.data
				}
				this.mainImg.push(img);
			},
			uploadremove(file) {
				if(file.name != undefined) {
					this.mainImg.splice(file.name, 1)
				} else {
					var reIdx = this.mainImg.findIndex((item, idx) => {
						return item.uid == file.uid
					})
					this.mainImg.splice(reIdx, 1)
				}
			},
		}
	}
</script>

<style>
	#cards .modal-dialog {
		left: 25% !important;
		top: 5% !important;
	}
	
	.el-picker-panel {
		z-index: 10051 !important;
	}
	
	.el-upload__input {
		display: none !important;
	}
	
	.el-upload-list__item-actions i {
		color: white !important;
	}
</style>